﻿using System;
using System.Text;
using System.Net.Sockets;
using System.Diagnostics;

namespace FLKRP.WP7.Server.Server
{
    internal class Client : IDisposable
    {
        Socket _socket;

        public event EventHandler SocketClosed;

        byte[] _readBuffer;

        public Client(Socket socket)
        {
            _socket = socket;

            _readBuffer = new byte[100];
        }
      

        public int BytesAvailable
        {
            get
            {
                if (_socket != null)
                    return _socket.Available;
                else
                    return 0;
            }
        }

        public void SendEndOfPacket()
        {
            _socket.Send(new byte[] { 0x0 }, 1, SocketFlags.None);
        }

        public void SendData(byte[] data)
        {
            if (_socket != null)
            {
                try
                {
                    _socket.Send(data);
                }
                catch (Exception ex)
                {
                    Close();
                    _socket = null;
                    SocketClosed(this, null);
                 
                }
            }
        }

        public void ReadBytes()
        {
            if (BytesAvailable > 0)
            {
                if (_socket != null)
                {
                    var bytesRead = _socket.Receive(_readBuffer, 100, SocketFlags.None);
                    var response = Encoding.UTF8.GetString(_readBuffer, 0, bytesRead);

                    Debug.WriteLine("Bytes Read " + response);
                }
            }
        }

        public void Close()
        {
            if (_socket == null)
                throw new NullReferenceException();

            try
            {
                _socket.Shutdown(SocketShutdown.Both);
                _socket.Close();
            }
            catch { }

            _socket = null;
        }

        public void Dispose()
        {
            if (_socket != null)
                Close();
        }
    }
}
